<template>
	<view class="publish-box bai left clearfix">
		<children-top page="/pages/index/index"></children-top>
		<view class="publish-content left clearfix">
			<view class="publish-left clearfix left relative">
				<view class="publish-left-title left">
					上传作品
				</view>
				<view class="publish-input-box left clearfix bai">
				<!--上传作品-->
				<view class="publish-upload left clearfix" @click="uploadFile()" v-if="percent == 0 && !filePath">
					<label>
						<uni-icons type="icon-shangchuan5" color="#999" size="18" custom-prefix="iconfont"></uni-icons>
					</label>
					<label>
						上传视频/图片
					</label>
				</view>
				
				<view class="publish-upload left clearfix relative" v-if="filePath && fileType == 'image'" style="height:auto;line-height:0;">
					<image :src="filePath" mode="aspectFit"></image>
					<view class="publish-label-close absolute" @click="removeFilePath(filePath)">
						<uni-icons type="closeempty" size="10" color="#fff"></uni-icons>
					</view>
				</view>
				
				<view class="publish-upload left clearfix relative" v-if="filePath && fileType == 'video'" style="height:auto;line-height:0;">
					<video :src="filePath" :style="'width:'+videoShowWidth+'px;height:'+videoShowHeight+'px'" object-fit="fill"></video>
					<view class="publish-label-close absolute" @click="removeFilePath(filePath)">
						<uni-icons type="closeempty" size="10" color="#fff"></uni-icons>
					</view>
				</view>
				
				
				<view class="publish-upload left clearfix" @click="uploadFile()" v-if="percent > 0 && percent < 100 && !filePath">
					<zmt-circular-progress :width="70" :height="70" style="margin-top:15px;" :percent="percent"></zmt-circular-progress>
				</view>
				
				
				
				
				
				
				<view class="publish-type left clearfix">
					<view class="publish-type-title left">
						作品标题
					</view>
					
					<view class="publish-type-item left">
						 <input placeholder="请输入作品标题" v-model="title"/>
					</view>
				</view>
				
				<view class="publish-type left clearfix">
					<view class="publish-type-title left">
						作品分类
					</view>
					
					<view class="publish-type-item left">
						 <uni-data-select
						      collection="works_class"
						      field="_id as value, title as text"
						      v-model="class"
						      :clear="true"
						    />
					</view>
				</view>
				
				<view class="publish-type left clearfix">
					<zmt-label @confirm="getLabel"></zmt-label>
				</view>
				</view>
				
				<view class="publish-submit left clearfix absolute" @click="submitForm()">
					确定发布
				</view>
				
			</view>
			
			<!--右边内容-->
			<view class="publish-right right clearfix">
				<view class="tim-left-title left">
					作品介绍
				</view>
				<view class="publish-right-content left clerarfix">
					<create-textarea @change="getContent" :fontTotalNumber="500"></create-textarea>
				</view>
			</view>
		</view>
		
		<login :show="showLogin"></login>
		<zmt-modal title="发布中" :show="modalShow" @close="modalShow = false" :content="modalContent"></zmt-modal>
	</view>
</template>


<style scoped>
	.publish-input-box{width:100%;height:550px;overflow: auto;}
	.publish-label-close{width:20px;height:20px;top:-5px;right:-5px;background:rgb(0,0,0,.5);line-height:15px;border-radius: 50%;text-align: center;cursor:pointer;}
	.publish-type-item input{width:calc(100% - 10px);padding-left:10px;height:100%;font-size:13px;border:1px solid #ddd;border-radius: 5px;}
	.tim-left-title{width:calc(100% - 20px);padding-left:20px;color: rgb(21, 27, 38);font-size: 18px;font-weight: 500;line-height: 28px;margin-top:20px;}
	.publish-right-content{width:100%;height:100%;}
	.publish-right{width:calc(100% - 400px);height:100%;background:#fff;border-radius:12px;}
	.publish-submit{width:80%;margin-left:10%;line-height:40px;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);color:#fff;text-align: center;border-radius: 10px;bottom:30px;left:0;right:0;cursor:pointer;}
	.publish-type-item{width:100%;height:40px;}
	.publish-type-title{width:90%;margin-left:10px;font-size:14px;font-weight:400;line-height:40px;height:40px;margin-bottom:10px;}
	.publish-type{width:calc(100% - 40px);margin-left:20px;min-height:70px;margin-top:30px;}
	.publish-upload label{font-size:14px;color:#999;}
	.publish-upload{text-align:center;width:calc(100% - 40px);height:100px;line-height:100px;margin-left:20px;background:rgba(150,150,150,.06);border:.5px dashed #ccc;color:rgba(224,245,255,.6);margin-top:20px;border-radius: 10px;cursor:pointer;}
	.publish-left-title{width:calc(100% - 20px);padding-left:20px;line-height:40px;height:40px;border-bottom:1px solid #efefef;font-size:14px;}
	.publish-left{width:380px;height:100%;background:#fff;border-radius: 12px;}
	body, uni-page-body{height:100%;}
	.publish-content{width: 96%;height: calc(100% - 110px);margin-left: 2%;margin-top: 70px;}
	.publish-box{width:100%;height:100%;}
	
</style>

<script>
	var db = uniCloud.database();
	var global = uniCloud.importObject('global',{customUI:true});
	export default {
		data() {
			return {
				modalShow:false,//显示提示
				modalContent:'作品发布中···',//提示内容
				userinfo:null,//登录用户数据
				showLogin:false,
				worksClassData:[],
				title:'',//作品标题
				percent:0,//上传进度
				content:'',
				filePath:'',//上传后的文件链接
				fileType:null,//上传后的文件类型
				class:'',//作品分类
				label:null,//标签
				fileInfo:null,//文件基本信息
				videoShowWidth:null,//显示的媒体的宽度
				videoShowHeight:null,//显示的媒体的高度
			}
		},
		created() {
			var that = this;
			uni.getStorage({
				key:'login-userinfo',
				success:function(res){
					var userinfo = res.data;
					if(!userinfo || !userinfo._id){
						console.log(1111);
						that.showLogin = true;
					}else{
						console.log(2222);
						that.userinfo = userinfo;
					}
				},
				fail() {
					console.log(3333);
					that.showLogin = true;
				}
			});
			
			
		},
		methods: {
			//删除作品
			removeFilePath(filePath){
				uni.showLoading({
					title:'删除中'
				})
				global.removeFileByPath(filePath).then(res=>{
					uni.hideLoading();
					this.filePath = null;
					this.percent = 0;
					uni.showToast({
						title:'删除成功',
						icon:'none',
						duration:2000
					})
				});
			},
			//获取内容
			getContent(e){
				this.content = e;
			},
			//上传文件
			uploadFile(){
				var that = this;
				uni.chooseFile({
					count:1,
					sourceType: ['album'],
					extension:['png','jpg','jpeg','gif','webp','bmp','mp4','avi','wmv','mov'],
					success: function (res) {
						console.log('res',res);
						var tempFilePath = res.tempFilePaths[0];
						var tempFiles = res.tempFiles[0];
						var fileType = that.checkFileFormat(tempFiles.name);
						if(fileType == 'video'){
							that.fileType = 'video';
							that.uploadVideo(tempFilePath,tempFiles);
						}else if(fileType == 'image'){
							that.fileType = 'image';
							that.uploadImage(tempFilePath,tempFiles);
						}
					}
				});
			},
			//发布视频
			async uploadVideo(tempFilePath,tempFiles){
				var that = this;
				var fileName = that.generateUUIDWithExtensionFromFileName(tempFiles.name);
				//获取视频基本信息
				var fileInfo = await that.getVideoInfoAsync(tempFilePath);
				console.log('视频信息',fileInfo);
				if(fileInfo.width > fileInfo.height){
					that.videoShowWidth = 280;
					that.videoShowHeight = fileInfo.height * (280/fileInfo.width).toFixed(2);
				}else{
					that.videoShowHeight = 280;
					that.videoShowWidth = fileInfo.width * (280/fileInfo.height).toFixed(2);
				}
				that.fileInfo = fileInfo;
				that.upload(tempFilePath,fileName);
				
			},
			//发布图片
			async uploadImage(tempFilePath,tempFiles){
				var that = this;
				var fileName = that.generateUUIDWithExtensionFromFileName(tempFiles.name);
				//获取上传文件的基本信息
				that.fileInfo = await that.getImageInfoAsync(tempFilePath);
				that.upload(tempFilePath,fileName);
				
			},
			//确定发布
			submitForm(){
				var that = this;
				var userinfo = that.userinfo;
				var content = that.content;
				var taskId = that.generateUUID;
				var fileInfo = that.fileInfo;
				var type = that.fileType;
				var filePath = that.filePath;
				var title = that.title;
				if(!filePath || !fileInfo){
					uni.showToast({
						title:'请上传作品',
						icon:'none',
						duration:2000
					})
					return false;
				}
				if(!title){
					uni.showToast({
						title:'请输入作品标题',
						icon:'none',
						duration:2000
					})
					return false;
				}
				
				if(!content){
					uni.showToast({
						title:'请输入作品介绍',
						icon:'none',
						duration:2000
					})
					return false;
				}
				
				that.modalShow = true;
				var ratio = that.calculateSimplifiedRatio(fileInfo.width,fileInfo.height);
				var data = {
					"app_title": "上传发布",
					"app_id": "",
					"uid": userinfo._id,
					"content": content,
					"task_id": taskId,
					"title":title,
					"size": fileInfo.width+'*'+fileInfo.height,
					"proportion": ratio,
					"type": type,
					"task_status": "SUCCEEDED",
					"task_status_text": "执行成功",
					"is_publish": true,
					"video_duration": Math.ceil(fileInfo.duration),
					"video_url": filePath
				}
				console.log('入库数据',data);
				//入库
				db.collection('create_result').add(data).then(res=>{
					that.modalContent = '发布成功';
					that.modalShow = false;
					uni.navigateTo({
						url:'/pages/works/works'
					})
				}).catch(err=>{
					console.log('发布失败',err);
				});
			},
			//根据宽高计算出宽高比
			calculateSimplifiedRatio(width, height) {
			    if (height === 0) {
			        return '高度不能为零';
			    }
			    const greatestCommonDivisor = this.gcd(width, height);
			    const simplifiedWidth = width / greatestCommonDivisor;
			    const simplifiedHeight = height / greatestCommonDivisor;
			    return `${simplifiedWidth}:${simplifiedHeight}`;
			},
			 gcd(a, b) {
			    while (b!== 0) {
			        let temp = b;
			        b = a % b;
			        a = temp;
			    }
			    return a;
			},
			//不带后缀名的uuid
			generateUUID() {
			    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			        const r = Math.random() * 16 | 0;
			        const v = c === 'x'? r : (r & 0x3 | 0x8);
			        return v.toString(16);
			    });
			},
			//上传
			upload(tempFilePath,fileName,info){
				var that = this;
				uniCloud.uploadFile({
				        filePath: tempFilePath,
				        cloudPath: fileName,
				        onUploadProgress: function(progressEvent) {
				          var percentCompleted = Math.round(
				            (progressEvent.loaded * 100) / progressEvent.total
				          );
						  
						  that.percent = percentCompleted;
				        },
				        success(res) {
							that.filePath = res.fileID;
						}
				      });
			},
			//获取图片基本信息
			getImageInfoAsync(src) {
			    return new Promise((resolve, reject) => {
			        uni.getImageInfo({
			            src,
			            success: (res) => {
			                resolve(res);
			            },
			            fail: (err) => {
			                reject(err);
			            }
			        });
			    });
			},
			//获取视频基本信息
			getVideoInfoAsync(src) {
			    return new Promise((resolve, reject) => {
			        uni.getVideoInfo({
			            src,
			            success: (res) => {
			                resolve(res);
			            },
			            fail: (err) => {
			                reject(err);
			            }
			        });
			    });
			},
			//判断文件是图片还是视频
			checkFileFormat(fileName) {
			    const extension = this.getFileExtension(fileName);
			    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
			    const videoExtensions = ['mp4', 'avi', 'mov', 'mkv', 'flv', 'wmv'];
			
			    if (imageExtensions.includes(extension)) {
			        return 'image';
			    } else if (videoExtensions.includes(extension)) {
			        return 'video';
			    }
			    return '未知格式';
			},
			//获取扩展名
			getFileExtension(fileName) {
			    const lastDotIndex = fileName.lastIndexOf('.');
			    if (lastDotIndex === -1) {
			        return '';
			    }
			    return fileName.slice(lastDotIndex + 1);
			},
			//带有后缀名的uuid
			generateUUIDWithExtensionFromFileName(fileName) {
			    const lastDotIndex = fileName.lastIndexOf('.');
			    let extension = '';
			    if (lastDotIndex !== -1) {
			        extension = fileName.slice(lastDotIndex + 1);
			    }
			    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			        let r = Math.random() * 16 | 0;
			        let v = c === 'x' ? r : (r & 0x3 | 0x8);
			        return v.toString(16);
			    });
			    if (extension) {
			        return `${uuid}.${extension}`;
			    }
			    return uuid;
			},
			//获取标签
			getLabel(label){
				this.label = label;
			}
		}
	}
</script>

